package service

import (
	"context"
	"template/api"
	"template/pkg/global"
	"template/pkg/page"

	"github.com/dromara/carbon/v2"
	"github.com/spf13/cast"
)

type IVoiceChatService interface {
	GetUserRechargeInfo(ctx context.Context, current, pageSize, unionId int64, price, operator, startTimes, endTimes string) (*page.Collection[*api.UserRechargeInfo], error)
}

type voiceChatService struct{}

func NewVoiceChatService() IVoiceChatService {
	return &voiceChatService{}
}

func (m *voiceChatService) GetUserRechargeInfo(ctx context.Context, current, pageSize, unionId int64, price, operator, startTimes, endTimes string) (*page.Collection[*api.UserRechargeInfo], error) {
	var (
		resultList                          []*api.UserRechargeInfo
		weekStartTime, weekEndTime, sqlDate string
		err                                 error
		total                               int
	)

	collectionDto := &page.Collection[*api.UserRechargeInfo]{}
	collectionDto.Page = cast.ToUint64(current)
	collectionDto.PageSize = cast.ToUint64(pageSize)
	mod := global.GFDB.Ctx(ctx).Model("user_info ui")

	if unionId > 0 {
		mod.Where("ubuj.union_id =?", unionId)
	}
	if len(operator) > 0 {
		switch operator {
		case "week":
			weekStartTime = carbon.Parse(startTimes).StartOfWeek().ToDateTimeString()
			weekEndTime = carbon.Parse(startTimes).EndOfWeek().ToDateTimeString()
			mod.Where("o.pay_time >= '%s' and o.pay_time <= '%s'", weekStartTime, weekEndTime)
		case "year":
			sqlDate = carbon.Parse(startTimes).Format("Y")
			mod.WhereLike("o.pay_time", "%"+sqlDate+"%")
		case "month":
			sqlDate = carbon.Parse(startTimes).Format("Y-m")
			mod.WhereLike("o.pay_time", "%"+sqlDate+"%")
		}
	}
	mod.Fields("ui.user_id,ui.user_no,ui.nickname,ui.country,ui.region,ui.gender,ud.device_type as device_name," +
		"GROUP_CONCAT(DISTINCT ubu.`name`) AS union_name,GROUP_CONCAT(DISTINCT ubuj.union_id) AS union_id,ui.created,u.updated,IFNULL(SUM(o.price),0) AS price")
	mod.LeftJoin("order o", "o.user_id = ui.user_id and o.`state` = 1")
	mod.LeftJoin("user u", "u.user_no = ui.user_id")
	mod.LeftJoin("user_broker_union ubu", "ui.user_id = ubu.user_id")
	mod.LeftJoin("user_device ud", "ui.user_id = ud.user_id")
	mod.LeftJoin("user_broker_union_join ubuj", "ui.user_id = ubuj.user_id and ubuj.status = 1")
	mod.Group("ui.user_id, ui.user_no, ui.nickname, ui.country, ui.region, ui.gender,ud.device_type,ui.created, u.updated")
	//mod.Order("price desc")
	mod.Limit(int(page.PageToOffset(cast.ToUint64(current), cast.ToUint64(pageSize))), cast.ToInt(pageSize))
	err = mod.ScanAndCount(&resultList, &total, false)
	collectionDto.TotalPage = page.GetTotalPage(cast.ToUint64(current), cast.ToUint64(pageSize), cast.ToInt64(total))

	collectionDto.Total = cast.ToInt64(total)
	collectionDto.List = resultList
	return collectionDto, err
}
